package com.jh.fcsm.service.sys.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jh.fcsm.beans.sys.SysRole;
import com.jh.fcsm.beans.sys.SysUserRole;
import com.jh.fcsm.beans.sys.vo.SysUserInfoVO;
import com.jh.fcsm.common.BaseServiceImpl;
import com.jh.fcsm.common.exception.ServiceException;
import com.jh.fcsm.dao.sys.SysUserRoleMapper;
import com.jh.fcsm.service.sys.RoleService;
import com.jh.fcsm.service.sys.UserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
@Transactional(readOnly = true)
public class UserRoleServiceImpl extends BaseServiceImpl<SysUserRoleMapper, SysUserRole> implements UserRoleService {

    @Autowired
    private RoleService roleService;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    /**
     * 保存或更新用户角色
     *
     * @param
     * @return
     */
    @Override
    @Transactional(readOnly = false)
    public void saveOrUpdateUserRole(String roleId, String[] userIds) throws ServiceException {

        if (roleId == null) {
            return;
        }

        /**** saveAll role to userId ***/
        for (String userId : userIds) {
            /**** delete all by userId ***/
            Example example = new Example(SysUserRole.class);
            example.createCriteria().andEqualTo("userId", userId).andEqualTo("roleId", roleId);
            List<SysUserRole> sysUserRoles = this.mapper.selectByExample(example);
            if (!CollectionUtils.isEmpty(sysUserRoles)) {
                continue;
            }
            if (userId != null) {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                this.mapper.insert(userRole);
            }
        }
    }

    /**
     * 查询用户角色列表
     */
    @Override
    public List<SysUserRole> list(String userId) {

        Example example = new Example(SysUserRole.class);
        if (userId == null) {
            userId = "-1";
        }
        example.createCriteria().andEqualTo("userId", userId);

        List<SysUserRole> userRoleList = this.selectByExample(example);
        return userRoleList;
    }

    /**
     * 根据角色编码查询同一个城市公司下的用户角色列表
     *
     * @return
     */
    @Override
    public List<SysUserRole> listByRoleCode(String roleCode) {

        if (StringUtils.isEmpty(roleCode)) {
            return null;
        }

        SysRole queryRole = new SysRole();
        queryRole.setRoleCode(roleCode);
        SysRole role = this.roleService.selectOne(queryRole);

        if (role == null) {
            throw new ServiceException("角色不存在");
        }

        Example example = new Example(SysUserRole.class);
        if (StringUtils.isBlank(roleCode)) {
            roleCode = "-1";
        }
        example.createCriteria().andEqualTo("roleId", role.getId());

        return this.selectByExample(example);
    }

    @Override
    public PageInfo<SysUserInfoVO> pageByRoleCodeAndName(Integer pageNum, Integer pageSize, String roleCode,
                                                         String userName) {
        if (StringUtils.isEmpty(roleCode)) {
            return null;
        }
//		List<String> userNames = new ArrayList<>();
//		if (!StringUtils.isBlank(userName)){
//			userNames = Arrays.asList(userName.split("\\s+"));
//		}
        // ** 2018-11-28 by szx */
        SysRole queryRole = new SysRole();
        if (StringUtils.isBlank(roleCode)) {
            roleCode = "-1";
        }
        queryRole.setRoleCode(roleCode);
        SysRole role = this.roleService.selectOne(queryRole);
        if (role == null) {
            throw new ServiceException("角色不存在");
        }

        PageHelper.startPage(pageNum, pageSize);
        if (StringUtils.isEmpty(userName.trim())) {
            throw new ServiceException("请输入查询条件");
        }
        String[] userNames = userName.trim().split(" ");
        List<SysUserInfoVO> sysUserRoles = this.mapper.findByRoleIdAndName(role.getId(), userNames);
        return new PageInfo<>(sysUserRoles);
    }

    @Override
    public void deleteByRoleId(String roleId) {
        Example example = new Example(SysUserRole.class);
        example.createCriteria().andEqualTo("roleId", roleId);
        this.mapper.deleteByExample(example);
    }

    @Override
    public void deleteByUserId(String userId) {
        if (userId == null) {
            throw new ServiceException("用户id不能为空!");
        }
        Example example = new Example(SysUserRole.class);
        example.createCriteria().andEqualTo("userId", userId);
        this.mapper.deleteByExample(example);
    }

    @Override
    public void deleteByRoleIdAndUserId(String roleId, String userId) {
        if (userId == null) {
            throw new ServiceException("用户id不能为空!");
        }
        if (roleId == null) {
            throw new ServiceException("角色id不能为空!");
        }
        Example example = new Example(SysUserRole.class);
        example.createCriteria().andEqualTo("userId", userId).andEqualTo("roleId", roleId);
        List<SysUserRole> sysUserRoles = this.mapper.selectByExample(example);
        if (CollectionUtils.isEmpty(sysUserRoles)) {
            throw new ServiceException("角色下不存在该用户!");
        }
        this.mapper.deleteByExample(example);
    }

    @Override
    public void swtichStatus(String roleId, String userId, String status) {
        Example example = new Example(SysUserRole.class);
        example.createCriteria().andEqualTo("userId", userId).andEqualTo("roleId", roleId);
        List<SysUserRole> sysUserRoles = this.mapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(sysUserRoles)) {
            for (SysUserRole sysUserRole : sysUserRoles) {
                this.mapper.updateByPrimaryKeySelective(sysUserRole);
            }
        }
    }

    /**
     * 用户下添加角色
     */
    @Override
    @Transactional(readOnly = false)
    public void saveOrUpdateRole(String userId, List<String> roleIds) {
        if (userId == null) {
            throw new ServiceException("非法请求");
        }
        // 先删除所有角色
        Example example = new Example(SysUserRole.class);
        example.createCriteria().andEqualTo("userId", userId);
        sysUserRoleMapper.deleteByExample(example);
        // 在添加角色
        if (!CollectionUtils.isEmpty(roleIds)) {
            for (String roleId : roleIds) {
                SysUserRole userRole = new SysUserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(userId);
                sysUserRoleMapper.insert(userRole);
            }

        }
    }
}
